package workqueues;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 任务所有好事，多个任务
 */
public class NewTask {
    private final static String TASK_QUEUE_NAME = "task_queue";

    public static void main(String[] args) {
        try {
            //创建连接工厂
            ConnectionFactory factory = new ConnectionFactory();
            //设置rabbitmq地址
            factory.setHost("127.0.0.1");
            factory.setUsername("admin");
            factory.setPassword("admin");
            //建立连接
            Connection connection = factory.newConnection();
            //获得信道
            Channel channel = connection.createChannel();
            //声明队列
            channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);
            //发送消息
            for (int i = 0; i < 10; i++) {
                String message;
                if (i %2 == 0) {
                    message = i + "...";
                }else{
                    message = String.valueOf(i);
                }
                channel.basicPublish("", TASK_QUEUE_NAME, null, message.getBytes("UTF-8"));
                System.out.println(" [x] 消息发送成功 '" + message + "'");
            }
            //关闭连接
            channel.close();
            connection.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }
}
